﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace treePainter
{
    public partial class TreePainter : Form
    {
        private Graphics graphics;
        double per1 = 0.6;
        double per2 = 0.7;
        double th1 = 40 * Math.PI / 180;
        double th2 = 30 * Math.PI / 180;
        const double PI = Math.PI;
        Random random = new Random();

        public TreePainter()
        {
            InitializeComponent();
            this.Paint += new PaintEventHandler(this.TreePainter_Load);
        }

        private void TreePainter_Load(object sender, PaintEventArgs e)
        {

            graphics = e.Graphics;
            DrawTree(10, this.Width / 2, this.Height * 4 / 5, Height/5, -PI / 2);
        }

        private void Repaint_Click(object sender, EventArgs e)
        {
            this.Invalidate();
        }

        private void DrawTree(int n, double x0, double y0, double length, double th)
        {
            if (n == 0)
            {
                return;
            }

            double x1 = x0 + length * Math.Cos(th);
            double y1 = y0 + length * Math.Sin(th);

            DrawLine(n, x0, y0, x1, y1, n / 2);

            DrawTree(n - 1, x1, y1, per1 * length * (0.5 + RandDouble()), th + th1 * (0.5 + RandDouble()));
            DrawTree(n - 1, x1, y1, per2 * length * (0.4 + RandDouble()), th - th2 * (0.5 + RandDouble()));
            if (RandDouble() > n/20.0)
            {
                DrawTree(n - 1, x1, y1, per2 * length * (0.4 + RandDouble()), th - th2 * (0.5 + RandDouble()));
            }
        }

        private void DrawLine(int n, double x0, double y0, double x1, double y1, int width)
        {
            if (n==1)
            {
                graphics.DrawLine(new Pen(Color.Green, width), (int)x0, (int)y0, (int)x1, (int)y1);
                //graphics.DrawLine(new Pen(Color.FromArgb(RandInt(), RandInt(), RandInt()), width), (int)x0, (int)y0, (int)x1, (int)y1);
            }
            else
            {
                graphics.DrawLine(new Pen(Color.BurlyWood, width), (int)x0, (int)y0, (int)x1, (int)y1);
            }
        }

        private double RandDouble()
        {
            return random.NextDouble();
        }

        private int RandInt()
        {
            return random.Next(0, 255);
        }
    }
}
